import React, {MutableRefObject, useContext, useEffect, useRef, useState} from 'react';
import type { InputRef } from 'antd';
import {Button, Form, Input, message, Pagination, Popconfirm, Table,Switch} from 'antd';
import type { FormInstance } from 'antd/es/form';
import {deleteRole, getRole, paginate, updateEnable} from "../../../api/role";
import withModal from "../../../components/WithModal";
import UsersForm from "../User/UsersForm";
import RoleForm from "./RoleForm";
const EditableContext = React.createContext<FormInstance<any> | null>(null);

interface Item {
    name:String,
    remark:String,
    details:String,
    key:String,
    id:number,
    enable:boolean|undefined,
}
interface RoleType{
    name:String,
    remark:String,
    details:String,
    key:String,
    id:number,
    enable:boolean|undefined,
}
interface EditableRowProps {
    index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};

interface EditableCellProps {
    title: React.ReactNode;
    editable: boolean;
    children: React.ReactNode;
    dataIndex: keyof Item;
    record: Item;
    handleSave: (record: Item) => void;
}

const EditableCell: React.FC<EditableCellProps> = ({
                                                       title,
                                                       editable,
                                                       children,
                                                       dataIndex,
                                                       record,
                                                       handleSave,
                                                       ...restProps
                                                   }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef<InputRef>(null);
    const form = useContext(EditableContext)!;

    useEffect(() => {
        if (editing) {
            inputRef.current!.focus();
        }
    }, [editing]);

    const toggleEdit = () => {
        setEditing(!editing);
        form.setFieldsValue({ [dataIndex]: record[dataIndex] });
    };

    const save = async () => {
        try {
            const values = await form.validateFields();

            toggleEdit();
            handleSave({ ...record, ...values });
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };

    let childNode = children;

    if (editable) {
        childNode = editing ? (
            <Form.Item
                style={{ margin: 0 }}
                name={dataIndex}
                rules={[
                    {
                        required: true,
                        message: `${title} is required.`,
                    },
                ]}
            >
                <Input ref={inputRef} onPressEnter={save} onBlur={save} />
            </Form.Item>
        ) : (
            <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
                {children}
            </div>
        );
    }

    return <td {...restProps}>{childNode}</td>;
};

type EditableTableProps = Parameters<typeof Table>[0];

interface DataType {
    key: React.Key;
    name: string;
    age: string;
    address: string;
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

const Index: React.FC = () => {
    const [dataSource, setDataSource] = useState<DataType[]>([
        {
            key: '0',
            name: 'Edward King 0',
            age: '32',
            address: 'London, Park Lane no. 0',
        },
        {
            key: '1',
            name: 'Edward King 1',
            age: '32',
            address: 'London, Park Lane no. 1',
        },
    ]);
    const [roleList,setRoleList] = useState<RoleType[]>([])
    const [paginate,setPaginate] = useState({page:1,per_page:10,total:0})
    const [count, setCount] = useState(2);
    const [title, setTitle] = useState("新增角色");
    const [id, setId] = useState(0);
    const [visiable, setVisiable] = useState(false);
    useEffect(()=>{
        getRoleList(paginate)
    },[])
    const getRoleList = (paginate:any)=>{
        getRole(paginate).then(res=>{
            if(res.data.code===1){
                setPaginate({page:res.data.data.page,total:res.data.data.count,per_page: res.data.data.per_page})
                setRoleList(res.data.data.list)
            }
        })
    }

    const handleDelete = (id:number) => {

        deleteRole(id).then((res:any)=>{
            console.log(res.data)
            if(res.data.code===1){
                getRoleList(paginate)
                message.success(res.data.msg)
            }
        })

    };

    function handleEnable(id:number) {
        updateEnable(id).then(res=>{
            if(res.data.code==1) message.success(res.data.msg)
        })
    }

    const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
        {
            title: '名称',
            dataIndex: 'name',
            width: '30%',
            editable: true,
        },
        {
            title: '是否启用',
            dataIndex: 'enable',
            render: (_, record:any) =>

                dataSource.length >= 1 ? (
                    <Switch checkedChildren="开启" unCheckedChildren="关闭"
                            key={record.enable}
                            defaultChecked={record.enable}
                    onClick={()=>{handleEnable(record.id)}}
                    />
                ) : null,
        },
        {
            title: '备注',
            dataIndex: 'remark',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record: any ) =>
                dataSource.length >= 1 ? (
                    <div>
                    <Popconfirm title="确认删除?" onConfirm={() => handleDelete(record.id)} >
                        <Button type="default" style={{marginRight:20}}>删除</Button>
                    </Popconfirm>
                    <Button  type="primary" onClick={()=>{openEdit(record.id)}}>修改</Button>
                    </div>
                ) : null,
        },
    ];

    const handleAdd = () => {
        open()
    };

    const handleSave = (row: DataType) => {
    };

    const afterSubmit = (row:RoleType,isEdit:boolean) => {
        if(isEdit==true){
            console.log("修改")
            const newData:RoleType[] = [...roleList];
            const index = newData.findIndex((item:RoleType) => row.id === item.id);
            const item = newData[index];
            newData.splice(index, 1, {
                ...item,
                ...row,
            });
            setRoleList(newData);
        }
        if(isEdit==false){
            const newData:RoleType[] = [...roleList];
            newData.push(row)
            console.log("new_data",newData)
            setRoleList(newData);
        }
        //getRoleList(paginate)
        close();
    };
    const close = () => {
        setVisiable(false)
    }

    const open = () => {
        setId(0)
        setTitle("新增角色")
        setVisiable(true)
    }
    const openEdit = (id:number) => {
        setTitle("修改角色")
        setId(id)
        setVisiable(true)
    }
    //点击确定提交表单
    const submit = (ref: MutableRefObject<FormInstance>) => {
        ref.current.submit();
    };
    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    const columns = defaultColumns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: DataType) => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave,
            }),
        };
    });
    const RoleFormModal = withModal({title}, {afterSubmit,id})(React.forwardRef(RoleForm));

    return (
        <div>
            <Button onClick={handleAdd} type="primary" style={{ marginBottom: 16 }}>
                新增
            </Button>
            <RoleFormModal visible={visiable} onCancel={close} onOk={submit} />
            <Table
                pagination={false}
                components={components}
                rowClassName={() => 'editable-row'}
                bordered
                dataSource={roleList}
                rowKey ={(roleList:any)=>roleList.id}
                columns={columns as ColumnTypes}
            />
            <Pagination current={paginate.page}
                        style={{ display: 'flex',marginTop: '25px',justifyContent: 'right'}}
                        total={paginate.total} onChange={(page:number,perPage:number)=>{getRoleList({page:page,per_page:perPage,total:0})}}  />
        </div>
    );
};

export default Index;
